package util

import (
	"context"
	"fmt"
	"io"
	"mime/multipart"
	"os"

	"github.com/golang-jwt/jwt/v4"
)

// jwt 生成token
func GetJwtToken(secretKey, userName string, isAdmin uint32, iat, seconds int64) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["user_name"] = userName
	claims["is_admin"] = isAdmin
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

// 验证管理员和非管理员登录
func IsAdmin(ctx context.Context) bool {
	return fmt.Sprintf("%v", ctx.Value("is_admin")) == "1"
}

func IsNotAdmin(ctx context.Context) bool {
	return fmt.Sprintf("%v", ctx.Value("is_admin")) == "2"
}

// 讲读取到文件 返回一个[]byte
func ReadSelfFile(f multipart.File) ([]byte, error) {
	var chunk []byte
	buf := make([]byte, 1024)
	for {
		//从file读取到buf中
		n, err := f.Read(buf)
		if err != nil && err != io.EOF {
			fmt.Println("read buf fail", err)
		}
		//说明读取结束
		if n == 0 {
			break
		}
		//读取到最终的缓冲区中
		chunk = append(chunk, buf[:n]...)
	}
	return chunk, nil
}

// 传入path 和 []byte{}, 覆盖的方式更新文件
func CreateSelfFile(path string, fileByte []byte) error {
	file, err := os.Create(path)
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = file.Write(fileByte)
	if err != nil {
		return err
	}
	return nil
}
